/**
 * 
 */
package org.azdroid.kit.net;

import org.azdroid.kit.net.Packet.Type;

import android.content.Context;
import android.util.Log;


/**
 * JSON请求HTTP客户端
 * 
 * @author hljdrl@gmail.com
 * 
 */
public class JSONAsClient extends HttpAsClient {

	private JSONPacket mJSONPacket;
	private String TAG = "JsonAsClient";

	/**
	 * @param packet
	 *            JSON数据请求实体
	 * @param context
	 *            上下文
	 */
	public JSONAsClient(JSONPacket packet, Context context) {
		super(packet.getTaskId(), packet.getUrl(), context);
		mJSONPacket = packet;
		setSendListNameValuePair(mJSONPacket.getSendBody());

	}

	@Override
	public synchronized void processResult(final byte[] bytes) {
		super.processResult(bytes);
		p("processResult().....");
		final ResultListener callback = getResultListener();
		if (callback instanceof JSONResultListener) {
			JSONResultListener call = (JSONResultListener) callback;
			if (bytes != null && mState == State.SUCC) {
				String strings = new String(bytes, 0, bytes.length);
				Log.d(TAG, strings);
				mJSONPacket.setType(Type.RESULT);
				mJSONPacket.parseJSONBody(strings);
				call.onResultSucc(mState, mJSONPacket);

			} else {
				call.onResultFail(mState, httpException);
			}
		} else if (callback instanceof DataResultListener) {
			try {
				DataResultListener call = (DataResultListener) callback;
				if (bytes != null && mState == State.SUCC) {
					call.onResultSucc(mState, getTaskId(), bytes);
				} else {
					call.onResultFail(mState, getTaskId(), httpException);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
